package com.reggie.handler;

import com.reggie.constant.MessageConstant;
import com.reggie.exception.BaseException;
import com.reggie.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     */
    @ExceptionHandler
    public R<String> excptionHandler(BaseException ex){
        log.error("捕获到业务异常为：" + ex.getMessage());
        return R.error(ex.getMessage());
    }

    /**
     * 捕获数据库唯一值异常
     */
    @ExceptionHandler
    public R<String> excptionHadler(SQLIntegrityConstraintViolationException ex){
        log.error("捕获到数据库异常为：" + ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")){
            String name = ex.getMessage().split(" ")[2];
            return R.error(name + "已存在");
        }
        return R.error(MessageConstant.UNKNOWN_ERROR);
    }
}
